import React, { useState, useEffect, useRef } from 'react';
import { Button, Space, message, Form, Input, DatePicker, Select, Modal } from 'antd';
import {
  DownloadOutlined,
  DeleteOutlined,
  EditOutlined,
  CloudUploadOutlined,
  PlusOutlined,
  ClockCircleOutlined,
  StopOutlined,
  LeftOutlined,
  RightOutlined
} from '@ant-design/icons';
import request from '@/utils/request';
import { useNavigate } from 'react-router-dom';
import DraggableTable from '@/components/DraggableTable';
import Breadcrumb from '@/components/Breadcrumb';
import './PDSDataManager.css';

const PDSDataManager: React.FC = () => {
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [tableData, setTableData] = useState<any[]>([]);
  const [tableLoading, setTableLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [form] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [batchDeleteLoading, setBatchDeleteLoading] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editRecord, setEditRecord] = useState<any>(null);
  const [editModalLoading, setEditModalLoading] = useState(false);

  // 选项数据状态
  const [filterOptions, setFilterOptions] = useState({
    task_type: [],
    dm_zhname: [],
    data_level: [],
    release_status: []
  });

  // 添加定时发布相关状态
  const [scheduleModalVisible, setScheduleModalVisible] = useState(false);
  const [scheduleModalLoading, setScheduleModalLoading] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<any>(null);
  const [scheduledTime, setScheduledTime] = useState<any>(null);
  const [isActionColumnCollapsed, setIsActionColumnCollapsed] = useState(false);

  const navigate = useNavigate();

  // 表格容器ref和滚动高度
  const tableContainerRef = useRef(null);
  const [tableScrollY, setTableScrollY] = useState(0);

  // 操作列渲染函数
  const renderActionColumn = (_, record) => {
    if (isActionColumnCollapsed) {
      return (
        <Space size="small" style={{ justifyContent: 'center' }}>
          <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)} title="编辑" />
          <Button size="small" icon={<DownloadOutlined />} onClick={() => handleDownload(record)} title="下载" />
          <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)} title="删除" />
          {record.release_status === 0 && (
            <>
              <Button size="small" type="primary" icon={<CloudUploadOutlined />} onClick={() => handleImmediatePublish(record)} title="立即发布" />
              <Button size="small" type="primary" icon={<ClockCircleOutlined />} onClick={() => handleSchedulePublish(record)} title="定时发布" />
            </>
          )}
          {record.release_status === 3 && (
            <Button size="small" type="primary" danger icon={<StopOutlined />} onClick={() => handleCancelPublish(record)} title="取消定时发布" />
          )}
        </Space>
      );
    }
    
    return (
      <Space>
        <Button size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
          编辑
        </Button>
        <Button size="small" icon={<DownloadOutlined />} onClick={() => handleDownload(record)}>
          下载
        </Button>
        <Button size="small" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record)}>
          删除
        </Button>
        {record.release_status === 0 && (
          <>
            <Button size="small" type="primary" icon={<CloudUploadOutlined />} onClick={() => handleImmediatePublish(record)}>
              立即发布
            </Button>
            <Button size="small" type="primary" icon={<ClockCircleOutlined />} onClick={() => handleSchedulePublish(record)}>
              定时发布
            </Button>
          </>
        )}
        {record.release_status === 3 && (
          <Button size="small" type="primary" danger icon={<StopOutlined />} onClick={() => handleCancelPublish(record)}>
            取消定时发布
          </Button>
        )}
      </Space>
    );
  };

  // columns用useState管理
  const [columns, setColumns] = useState([
    {
      title: '数据集名称',
      dataIndex: 'dataset_name',
      key: 'dataset_name',
      width: 400,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '任务型号',
      dataIndex: 'task_type',
      key: 'task_type',
      width: 150,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '载荷',
      dataIndex: 'dm_zhname',
      key: 'dm_zhname',
      width: 150,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '数据级别',
      dataIndex: 'data_level',
      key: 'data_level',
      width: 150,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '采集开始时间',
      dataIndex: 'collection_time_start',
      key: 'collection_time_start',
      width: 200,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '采集结束时间',
      dataIndex: 'collection_time_end',
      key: 'collection_time_end',
      width: 200,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '文件个数',
      dataIndex: 'files_count',
      key: 'files_count',
      width: 150,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '数据总量(MB)',
      dataIndex: 'files_size',
      key: 'files_size',
      width: 180,
      ellipsis: true,
      render: (text) => formatFileSize(text)
    },
    {
      title: '简要描述',
      dataIndex: 'dataset_describe',
      key: 'dataset_describe',
      width: 400,
      ellipsis: true,
      render: (text) => (text ? text : '-')
    },
    {
      title: '发布状态',
      dataIndex: 'release_status',
      key: 'release_status',
      width: 150,
      ellipsis: true,
      render: (status) => {
        const statusMap = {
          0: '未发布',
          1: '已发布',
          2: '发布中'
        };
        return statusMap[status] || '-';
      }
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: 200,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '操作',
      key: 'action',
      width: 400,
      fixed: 'right',
      align: 'center' as const,
      render: (_, record) => renderActionColumn(_, record)
    }
  ]);

  // 获取筛选选项
  const fetchFilterOptions = async () => {
    try {
      const response = await request.get('/PDS/DataSetFilterSearch');
      if (response.status === 200) {
        setFilterOptions(response.data.data);
      }
    } catch (error) {
      message.error(error instanceof Error ? error.message : '获取筛选选项失败');
    }
  };

  useEffect(() => {
    fetchFilterOptions();
  }, []);

  // 监听操作列收起展开状态变化
  useEffect(() => {
    setColumns((prevColumns) => {
      if (!prevColumns) return prevColumns;
      return prevColumns.map((col) => {
        if (col.key === 'action') {
          return {
            ...col,
            width: isActionColumnCollapsed ? 200 : 400,
            render: renderActionColumn
          };
        }
        return col;
      });
    });
  }, [isActionColumnCollapsed]);

  // 获取数据集列表
  const fetchData = async () => {
    setTableLoading(true);
    try {
      const formValues = form.getFieldsValue();
      const response = await request.get('/PDS/DataSetListSearch', {
        params: {
          page: current,
          page_size: pageSize,
          task_type: formValues.task_type,
          dm_zhname: formValues.dm_zhname,
          data_level: formValues.data_level,
          release_status: formValues.release_status,
          create_time__gte: formValues.create_time_range?.[0]?.format('YYYY-MM-DD 00:00:00'),
          create_time__lte: formValues.create_time_range?.[1]?.format('YYYY-MM-DD 23:59:59'),
          dataset_name: formValues.dataset_name
        }
      });
      if (response.status === 200) {
        const { list, count } = response.data.data;
        setTableData(
          list.map((item: any) => ({
            ...item,
            key: item.id,
            name: item.dataset_name,
            description: item.dataset_describe,
            taskType: item.task_type,
            payload: item.dm_zhname,
            dataLevel: item.data_level,
            collectStart: item.collection_time_start,
            collectEnd: item.collection_time_end,
            fileCount: item.files_count,
            dataSize: item.files_size,
            publishState: item.release_status === 1 ? '已发布' : item.release_status === 0 ? '未发布' : '发布中',
            createTime: item.create_time
          }))
        );
        setTotal(count);
      }
    } catch (error) {
      message.error(error instanceof Error ? error.message : '获取数据集列表失败');
    } finally {
      setTableLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [current, pageSize]);

  // 筛选表单提交
  const onFinish = () => {
    setCurrent(1);
    fetchData();
  };

  // 编辑
  const handleEdit = (record: any) => {
    navigate(`/pds-data?id=${record.id}`);
  };

  // 下载
  const handleDownload = async (record: any) => {
    try {
      const response = await request.post('/PDS/DataSetDownload', {
        dataset_ids: [record.id]
      });
      if (response.status === 200) {
        message.success('请到“下载订单”中查看拟下载数据的准备情况', 5);
      }
    } catch (error) {
      message.error(error instanceof Error ? error.message : '下载失败');
    }
  };

  // 删除
  const handleDelete = (record: any) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除数据集 "${record.name}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await request.post('/PDS/DataSetDelete', { dataset_ids: [record.id] });
          if (response.status === 200) {
            message.success('删除成功');
            fetchData();
          }
        } catch (error) {
          message.error(error instanceof Error ? error.message : '删除失败');
        }
      }
    });
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的数据集');
      return;
    }
    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个数据集吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        setBatchDeleteLoading(true);
        try {
          const response = await request.post('/PDS/DataSetDelete', { dataset_ids: selectedRowKeys });
          if (response.status === 200) {
            message.success('批量删除成功');
            setSelectedRowKeys([]);
            fetchData();
          }
        } catch (error) {
          message.error(error instanceof Error ? error.message : '批量删除失败');
        } finally {
          setBatchDeleteLoading(false);
        }
      }
    });
  };

  // 立即发布
  const handleImmediatePublish = async (record: any) => {
    try {
      const response = await request.post('/PDS/DataSetRelease', {
        release_type: 1,
        files: {
          dataset_ids: [record.id]
        }
      });
      if (response.status === 200) {
        message.success('发布成功');
        fetchData();
      }
    } catch (error) {
      message.error(error instanceof Error ? error.message : '发布失败');
    }
  };

  // 打开定时发布弹窗
  const handleSchedulePublish = (record: any) => {
    setCurrentRecord(record);
    setScheduleModalVisible(true);
  };

  // 确认定时发布
  const handleScheduleConfirm = async () => {
    if (!scheduledTime) {
      message.warning('请选择定时发布时间');
      return;
    }

    setScheduleModalLoading(true);
    try {
      const response = await request.post('/PDS/DataSetRelease', {
        release_type: 2,
        scheduled_release_time: scheduledTime.format('YYYY-MM-DD HH:mm:ss'),
        files: {
          dataset_ids: [currentRecord.id]
        }
      });
      if (response.status === 200) {
        message.success('定时发布设置成功');
        setScheduleModalVisible(false);
        setScheduledTime(null);
        fetchData();
      }
    } catch (error) {
      message.error(error instanceof Error ? error.message : '定时发布设置失败');
    } finally {
      setScheduleModalLoading(false);
    }
  };

  // 取消发布
  const handleCancelPublish = async (record: any) => {
    Modal.confirm({
      title: '确认取消发布',
      content: `确定要取消发布数据集 "${record.name}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await request.post('/PDS/DataSetCancelRelease', {
            dataset_ids: [record.id]
          });
          if (response.status === 200) {
            message.success('取消发布成功');
            fetchData();
          }
        } catch (error) {
          message.error(error instanceof Error ? error.message : '取消发布失败');
        }
      }
    });
  };

  // 表格选择配置
  const rowSelection = {
    selectedRowKeys,
    columnWidth: 50,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    }
  };

  // 工具函数：只将字节B换算为MB，始终显示为MB
  function formatFileSize(bytes) {
    if (bytes === undefined || bytes === null || bytes === '' || isNaN(bytes)) {
      return '-';
    }
    const mb = Number(bytes) / 1024 / 1024;
    return mb.toFixed(2) + ' MB';
  }

  // 计算表格滚动高度
  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      const containerHeight = tableContainerRef.current.clientHeight;
      const tableHeaderHeight = 89;
      const scrollHeight = containerHeight - tableHeaderHeight;
      setTableScrollY(scrollHeight);
      const body = tableContainerRef.current.querySelector('.ant-table-body');
      if (body) {
        body.style.height = Math.max(scrollHeight, 0) + 'px';
      }
    }
  };

  useEffect(() => {
    calculateTableScrollHeight();
    window.addEventListener('resize', calculateTableScrollHeight);
    return () => {
      window.removeEventListener('resize', calculateTableScrollHeight);
    };
  }, []);

  // 新建数据集
  const handleCreate = async () => {
    try {
      const response = await request.post('/PDS/DataSetCreate');
      if (response.status === 200) {
        message.success('创建成功');
        navigate(`/pds-data?id=${response.data.data.dataset_id}`);
      }
    } catch (error) {
      message.error(error instanceof Error ? error.message : '创建失败');
    }
  };

  return (
    <div className="pds-data-manager-container">
      <div style={{ position: 'absolute', width: '100%', display: 'flex', flexDirection: 'column', height: '100%' }}>
        <Breadcrumb text="PDS数据集管理" />
        <div className="content">
          {/* 筛选表单 */}
          <Form form={form} layout="inline" className="filter-form" onFinish={onFinish} labelCol={{ style: { width: 80 } }}>
            <Form.Item name="task_type" label="任务型号" style={{ width: 350 }}>
              <Select allowClear placeholder="请选择任务型号">
                {filterOptions.task_type.map((item: string) => (
                  <Select.Option key={item} value={item}>
                    {item}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="dm_zhname" label="载荷" style={{ width: 350 }}>
              <Select allowClear placeholder="请选择载荷">
                {filterOptions.dm_zhname.map((item: string) => (
                  <Select.Option key={item} value={item}>
                    {item}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="data_level" label="数据级别" style={{ width: 350 }}>
              <Select allowClear placeholder="请选择数据级别">
                {filterOptions.data_level.map((item: string) => (
                  <Select.Option key={item} value={item}>
                    {item}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="release_status" label="发布状态" style={{ width: 350 }}>
              <Select allowClear placeholder="请选择发布状态">
                {filterOptions.release_status.map((item: string | number) => {
                  const statusMap = {
                    0: '未发布',
                    1: '已发布',
                    2: '发布中'
                  };
                  return (
                    <Select.Option key={item} value={item}>
                      {statusMap[item] || item}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item label="采集时间" name="create_time_range" style={{ width: 350 }}>
              <DatePicker.RangePicker style={{ width: '100%' }} placeholder={['开始时间', '结束时间']} />
            </Form.Item>
            <Form.Item name="dataset_name" label="关键字" style={{ width: 350 }}>
              <Input placeholder="输入数据关键字" />
            </Form.Item>
            <Form.Item style={{ paddingLeft: 40 }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  筛选
                </Button>
                <Button
                  htmlType="button"
                  onClick={() => {
                    form.resetFields();
                    fetchData();
                  }}>
                  清除
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
        {/* 数据表格 */}
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <Button type="primary" danger onClick={handleBatchDelete} loading={batchDeleteLoading} disabled={selectedRowKeys.length === 0}>
              批量删除
            </Button>
            <Button style={{ marginLeft: 10 }} onClick={() => navigate('/release-history')}>
              发布历史
            </Button>
            <Button style={{ marginLeft: 10 }} onClick={() => navigate('/download-order')}>
              下载订单
            </Button>
          </div>

          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            新建数据集
          </Button>
        </div>
        <div className="pds-table-container" ref={tableContainerRef} style={{ flex: 1, overflow: 'hidden', position: 'relative' }}>
          <DraggableTable
            rowSelection={rowSelection}
            columns={columns}
            dataSource={tableData}
            pagination={{
              current,
              pageSize,
              total,
              showSizeChanger: true,
              pageSizeOptions: ['10', '20', '50'],
              onChange: (page, size) => {
                setCurrent(page);
                setPageSize(size);
              },
              showTotal: (total) => `共 ${total} 条`
            }}
            scroll={{ y: tableScrollY, x: 'max-content' }}
            bordered
            size="small"
            loading={tableLoading}
            onColumnsChange={setColumns}
          />
          <Button
            type="normal"
            size="small"
            icon={isActionColumnCollapsed ? <LeftOutlined /> : <RightOutlined />}
            onClick={() => setIsActionColumnCollapsed(!isActionColumnCollapsed)}
            style={{
              position: 'absolute',
              top: '8px',
              right: isActionColumnCollapsed ? '165px' : '355px',
              zIndex: 1000,
              borderRadius: '4px',
              fontSize: '12px',
              color: '#1890ff',
              gap: '0px',
            }}
          >
            {isActionColumnCollapsed ? '' : '收起'}
          </Button>
        </div>
        {/* 编辑弹窗（可后续补充表单内容） */}
        <Modal
          title="编辑数据集"
          open={editModalVisible}
          onCancel={() => setEditModalVisible(false)}
          footer={null}
          width={600}
          confirmLoading={editModalLoading}>
          {/* 这里可以放编辑表单 */}
          <div>编辑表单内容（待补充）</div>
        </Modal>
        {/* 定时发布弹窗 */}
        <Modal
          title="设置定时发布时间"
          open={scheduleModalVisible}
          onCancel={() => {
            setScheduleModalVisible(false);
            setScheduledTime(null);
          }}
          onOk={handleScheduleConfirm}
          confirmLoading={scheduleModalLoading}>
          <Form layout="vertical">
            <Form.Item label="定时发布时间" required>
              <DatePicker
                showTime
                style={{ width: '100%' }}
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择定时发布时间"
                value={scheduledTime}
                onChange={(value) => setScheduledTime(value)}
                disabledDate={(current) => current && current.valueOf() < Date.now()}
              />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </div>
  );
};

export default PDSDataManager;
